package com.program.beautymakeup.aop;

import com.program.beautymakeup.domain.vo.ResultInfo;
import com.program.beautymakeup.utils.ResultInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

/**
 * @author CaiKe
 * @date 2023/2/8 20:02
 */
@Slf4j
@ControllerAdvice
public class UserAuthExceptionHandler {

    @ResponseBody
    @ExceptionHandler(UserAuthException.class)
    public ResultInfo<String> handleUserAuthException(UserAuthException exception){
        log.error("Exception", exception);
        return ResultInfoUtil.build(401, exception.getMessage(), null);
    }

    /**
     * 拦截参数校验的异常
     *
     * @param e 校验异常
     * @return 返回结果
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultInfo<Void> notValidExceptionHandle(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Objects.requireNonNull(bindingResult.getFieldError());
        return ResultInfoUtil.buildError(404,
                bindingResult.getFieldError().getField() + " " + bindingResult.getFieldError().getDefaultMessage());
    }

}